import tkinter as tk
from tkinter import filedialog
import cv2
import numpy as np
from tensorflow.keras.models import load_model
from tkinter import messagebox, Canvas, Button, Label, Tk, Entry, Toplevel
import os
from PIL import Image, ImageDraw, ImageTk, ImageGrab
import tensorflow as tf

with tf.device('/CPU:0'):
# Load your pre-trained model for digit recognition
    model = load_model('mnist_model.h5')  # Replace with your model file path

# Function to perform digit recognition
    def recognize_digits(image_path):
        try:
            # Load the image
            image = cv2.imdecode(np.fromfile(image_path, dtype=np.uint8), -1)

            if image is None:
                raise ValueError("Failed to load image. Check image path and format.")

            # Convert to grayscale, resize, and prepare input for model
            gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            resized = cv2.resize(gray, (28, 28))
            input_data = resized.reshape(1, 28, 28, 1) / 255.0

            # Make predictions
            predictions = model.predict(input_data)
            digit = np.argmax(predictions)

            return digit

        except Exception as e:
            print(f"Error in recognize_digits: {e}")
            return None

    # Function to handle button click event (opens file dialog)
    def open_file_dialog():
        file_path = filedialog.askopenfilename()
        if file_path:
            digit = recognize_digits(file_path)
            if digit is not None:
                print(f"Predicted Digit: {digit}")
            else:
                print("Digit recognition failed.")

    # Create GUI window
    window = tk.Tk()
    window.title("Digit Recognition")
    window.geometry("300x100")

    # Create a button to open file dialog
    btn_open = tk.Button(window, text="Open Image", command=open_file_dialog)
    btn_open.pack(pady=20)

    # Run the GUI window
    window.mainloop()